﻿/**

 * Copyright (c) 2015-2016, FastDev 刘强 (fastdev@163.com) & Quincy.

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OF.Notify.DataHost.Cluster.Entity;
using OF.Notify.Entity;
using OF.DistributeService.Core.Common;

namespace OF.Notify.DataHost.Cluster.Disk
{
    public class DiskCollectionSyncMessageStore
    {
        internal int TempFileId = 0;
        internal byte topicEnum;
		internal TopicClusterContext topicContext;
		public DiskCollectionSyncMessageStore(byte topicEnum)
		{
				this.topicEnum = topicEnum;
				this.topicContext = ClusterContext.Get().GetTopicContext(topicEnum);
		}
		
        public void SafeTouchClusterTempPath(int nodeId, int clusterId)
        {
            string tempBasePath = topicContext.GetTempMessageBasePath(nodeId, clusterId);
            DiskVisitor.TryCreateDir(tempBasePath);
        }

        public void SaveSyncMessages(int nodeId, int clusterId, int collectionId, List<TopicMessage> msgs)
        {
            string tempPath = topicContext.GetTempMessagePath(nodeId, clusterId, collectionId) + "_" + Interlocked.Increment(ref TempFileId);
            DiskVisitor.EnsureFileDirectoryExists(tempPath);
            DiskVisitor.SafeDeleteFile(tempPath);
            using (FileStream fs = new FileStream(tempPath, FileMode.Append))
            {
                if (msgs != null)
                {
                    foreach (var msg in msgs)
                    {
                        var messageContent = msg.GetContent();
                        fs.Write(System.BitConverter.GetBytes((UInt16)(messageContent.Length)), 0, 2);
                        fs.Write(messageContent, 0, messageContent.Length);
                    }
                }
            }
            string destPath = topicContext.GetMessagePath(nodeId, collectionId);
            DiskVisitor.SafeMoveFile(tempPath, destPath);
        }

        public void SafeDeleteClusterTempPath(int nodeId, int clusterId)
        { 
            string tempBasePath = topicContext.GetTempMessageBasePath(nodeId, clusterId);
            DiskVisitor.SafeDeleteDir(tempBasePath);
        }

        public List<int> GetAllUnfinishedSyncClusterIds(int nodeId)
        { 
            return topicContext.GetAllTempMessageClusters(nodeId);
        }
    }
}
